package com.dhc.service.controller;

import com.dhc.service.annotation.Authorization;
import com.dhc.service.entity.AdminLogin;
import com.dhc.service.entity.vo.AdminLoginVo;
import com.dhc.service.service.AdminInfoService;
import com.dhc.service.utils.jwt.JwtUtils;
import com.dhc.service.utils.result.Result;
import lombok.NonNull;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sys/admin-info")
@CrossOrigin
public class AdminInfoController {

	@Autowired
	private AdminInfoService adminInfoService;

	/**
	 * 根据token取当前用户信息
	 *
	 * @param token
	 * @return
	 */
	@Authorization(code = 401, message = "登录状态异常，请重新登录")
	@GetMapping("getInfo")
	public Result getInfo(@Param("token") @NonNull String token) {
		String adminId = JwtUtils.getIdByToken(token);
		AdminLogin adminLogin = adminInfoService.getById(adminId);
		AdminLoginVo adminLoginVo = new AdminLoginVo();
		BeanUtils.copyProperties(adminLogin, adminLoginVo);
		return Result.ok().data("admin", adminLoginVo);
	}

	/**
	 * 判断该username是否已经被注册
	 * @param username
	 * @return
	 */
	@GetMapping("getCountByName")
	public Result getCountByName(@Param(value = "username") @NonNull String username) {
		int count = adminInfoService.getCountByName(username);
		if (count > 0) {
			return Result.error().message("用户名已被注册");
		} else {
			return Result.ok().message("当前用户名可用");
		}
	}
}
